package com.deuwise.system.controller;

import com.deuwise.common.utils.FileUtil;
import com.deuwise.common.utils.R;
import com.deuwise.common.utils.UploadProperties;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author hezhenhao
 * @date 2019-7-16
 */
@Api(tags = "系统APP信息模块", description = "APP信息模块")
@RequestMapping("api/app")
@RestController()
@CrossOrigin
public class AppController extends AbstractController {

    @Autowired
    UploadProperties uploadProperties;

    @ApiOperation(value = "投产环境apk最新版本信息")
    @GetMapping()
    public R select(){
        Map<String,String> resultMap = new HashMap<String,String>(16);
        try{
            String filepath = uploadProperties.getBasePath() + "/appFile";
            File file = new File(filepath);
            File[] tempList = file.listFiles();
            //临时最大版本号
            String maxVersion = "0";
            // 临时最大版本号的文件
            File maxTempFile = null;
            for (File file1 : tempList) {
                if(0 > file1.getName().indexOf("p_app-sl_")){
                    // 不存在产品包
                    continue;
                }
                //当前文件版本号
                String fileVersion = file1.getName().replace(".apk","")
                        //产品包
                        .replace("p_app-sl_","");
                // 比较版本号
                if(0 > compareVersion(maxVersion,fileVersion)){
                    // maxVersion 小于 fileVersion
                    maxVersion = fileVersion;
                    maxTempFile = file1;
                }
            }
            if(maxTempFile != null){
                return R.ok(resultFileMap(maxTempFile, maxVersion));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok(resultMap);
    }

    @ApiOperation(value = "测试环境apk最新版本信息")
    @RequestMapping(value = "/getDevApp", method = RequestMethod.GET)
    public R getDevApp(){
        Map<String,String> resultMap = new HashMap<String,String>(16);
        try{
            String filepath = uploadProperties.getBasePath() + "/appFile";
            File file = new File(filepath);
            File[] tempList = file.listFiles();
            //临时最大版本号
            String maxVersion = "0";
            // 临时最大版本号的文件
            File maxTempFile = null;
            for (File file1 : tempList) {
                if(0 > file1.getName().indexOf("d_app-sl_")){
                    // 不存在测试包
                    continue;
                }
                //当前文件版本号
                String fileVersion = file1.getName().replace(".apk","")
                        //测试包
                        .replace("d_app-sl_","");
                // 比较版本号
                if(0 > compareVersion(maxVersion,fileVersion)){
                    // maxVersion 小于 fileVersion
                    maxVersion = fileVersion;
                    maxTempFile = file1;
                }
            }
            if(maxTempFile != null){
                return R.ok(resultFileMap(maxTempFile, maxVersion));
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return R.ok(resultMap);
    }

    /**
     * apk文件信息拆分
     * @param file
     * @return
     */
    public Map<String,String> resultFileMap(File file, String maxVersion){
        DecimalFormat df1 = new DecimalFormat("0.00");
        Map<String,String> resultMap = new HashMap<String,String>(16);
        /*APP大小*/
        String fileSizeString  = df1.format((double) file.length() / 1048576) + "MB";
        resultMap.put("version",maxVersion);
        /*0:强制升级，1:点击升级*/
        resultMap.put("updateType","1");
        /*下载最新APK对应的链接*/
        resultMap.put("updateUrl",file.getName());
        resultMap.put("fileSize",fileSizeString);
        return resultMap;
    }

    /**
     * app下载
     * @param url appURL
     * @param request 请求体
     * @param response 响应体
     */
    @ApiOperation(value = "app下载")
    @ApiImplicitParam(name = "url", value = "文件url", dataType = "String", required = true, paramType = "path")
    @GetMapping("/appDownload/{url}")
    public void appDownload(@PathVariable String url, HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        try {
            if(url.indexOf(".apk") == -1){
                url = url + ".apk";
            }
            String filepath = uploadProperties.getBasePath() + "/appFile/" + url;
            File file = new File(filepath);
            fis = new FileInputStream(file);
            response.setHeader("Content-Disposition", "attachment; filename="+file.getName());
            response.addHeader("Content-Length", "" + file.length());
            IOUtils.copy(fis,response.getOutputStream());
            response.flushBuffer();
        } catch (FileNotFoundException e) {
            logger.error("AppController(appDownload)app文件不存在异常---->>>"+e.getMessage());
        } catch (IOException e) {
            logger.error("AppController(appDownload)app下载异常---->>>"+e.getMessage());
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    logger.error("AppController(appDownload)app下载流关闭异常---->>>"+e.getMessage());
                }
            }
        }
    }

    @ResponseBody
    @ApiOperation(value = "APP文件上传")
    @PostMapping("/appUpload")
    @RequiresPermissions("sys:app:upload")
    public R appUpload(@RequestParam("file")@ApiParam(value = "文件", required = true) MultipartFile file) {
        // APP目录
        String filePath= uploadProperties.getBasePath() + "/appFile/";
        String fileName = file.getOriginalFilename();
        if(0 > fileName.indexOf("p_app-sl_") && 0 > fileName.indexOf("d_app-sl_")){
            return R.error(200,"文件名称不合法！");
        }
        //判断文件是否存在
        File f = new File(filePath+fileName);
        if(f.exists()){
            return R.error(200,"此版本号apk已存在！");
        }
        try {
            FileUtil.uploadFile(file.getBytes(), filePath, fileName);
            return R.ok(filePath+fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error();
    }

    @ApiOperation(value = "apk信息列表")
    @RequestMapping(value = "/selectAppList", method = RequestMethod.GET)
    public R selectAppList(){
        List<Map<String,String>> result = new ArrayList<Map<String,String>>();
        DecimalFormat df1 = new DecimalFormat("0.00");
        try{
            String filepath = uploadProperties.getBasePath() + "/appFile";
            File file = new File(filepath);
            File[] tempList = file.listFiles();
            Arrays.sort(tempList);
            for (File file1 : tempList) {
                Map<String,String> resultMap = new HashMap<String,String>(16);
                //当前文件版本号
                String fileVersion = "0.0.1";
                try{
                    fileVersion = file1.getName().replace(".apk","")
                            //产品包
                            .replace("p_app-sl_","")
                            //测试包
                            .replace("d_app-sl_","")
                            .replace("app-sl_","");
                }catch (Exception e){
                    fileVersion = "0.0.1";
                }
                /*APP大小*/
                String fileSizeString  = df1.format((double) file1.length() / 1048576) + "MB";
                // 应用环境：p_app-sl_0.0.1 ： 生成包，d_app-sl_0.0.1：测试包
                String environment = "测试环境";
                if(-1 < file1.getName().indexOf("p_app-sl_")){
                    environment = "投产环境";
                }
                /*文件上传时间*/
                long time = file.lastModified();
                String ctime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(time));
                resultMap.put("environment",environment);
                resultMap.put("version",fileVersion);
                /*0:强制升级，1:点击升级*/
                resultMap.put("updateType","1");
                /*下载最新APK对应的链接*/
                resultMap.put("updateUrl",file1.getName());
                resultMap.put("fileSize",fileSizeString);
                resultMap.put("uploadTime",ctime);
                result.add(resultMap);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok(result);
    }

    @ResponseBody
    @ApiOperation("删除APP")
    @DeleteMapping()
    @RequiresPermissions("sys:app:del")
    public R deleteApp(@RequestParam String fileUrl){
        boolean result = false;
        try{
            String filepath = uploadProperties.getBasePath() + "/appFile/" + fileUrl;
            File file=new File(filepath);
            if(file.exists() && file.isFile()){
                result = file.delete();
            }
        }catch (Exception e){
        }
        return R.ok(result);
    }

    /**
     * apk版本号比较大小
     */
    public int compareVersion(String version1, String version2) {
        try{
            String[] v1 = version1.split("\\.");
            String[] v2 = version2.split("\\.");

            for ( int i = 0; i < Math.max(v1.length, v2.length); i++ ) {
                int num1 = i < v1.length ? Integer.parseInt( v1[i] ) : 0;
                int num2 = i < v2.length ? Integer.parseInt( v2[i] ) : 0;
                if ( num1 < num2 ) {
                    return -1;
                } else if ( num1 > num2 ) {
                    return +1;
                }
            }
        }catch (Exception e){
        }
        return 0;
    }
}
